﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows.Forms;

namespace POS.Framework
{
    public class FormFactory
    {
        public static void OpenForm(string childString, string title, Form main)
        {
            OpenForm(childString, title, string.Empty, main);
        }

        /// <summary>
        /// 打开窗体
        /// </summary>
        /// <param name="childString"></param>
        /// <param name="title"></param>
        /// <param name="tag"></param>
        public static void OpenForm(string childString, string title, object tag, Form main)
        {
            Form myChild = null;
            if (!ContainMDIChild(childString, main))
            {
                Assembly assembly = Assembly.GetExecutingAssembly();
                Type typForm = assembly.GetType(childString);
                Object obj = typForm.InvokeMember(
                    null,
                    BindingFlags.DeclaredOnly |
                    BindingFlags.Public | BindingFlags.NonPublic |
                    BindingFlags.Instance | BindingFlags.CreateInstance,
                    null,
                    title,
                    null);
                if (obj != null)
                {
                    myChild = obj as Form;
                    myChild.Text = title;
                    if (tag != null && tag.ToString()== "POP")
                    {
                        myChild.ShowDialog();
                        myChild.Focus();
                    }
                    else
                    {
                        myChild.MdiParent = main;
                        myChild.Tag = tag;
                        myChild.Show();
                        myChild.Focus();
                        //Main.xtraTabbedMdiManager.Pages[myChild].Image = ToolClassLibrary.Resource.exit_2011_01_01;
                    }
                }
            }
        }

        static bool ContainMDIChild(string childString, Form main)
        {
            Form myMDIChild = null;
            foreach (Form f in main.MdiChildren)
            {
                if (f.GetType().ToString() != childString) continue;
                myMDIChild = f;
                break;
            }
            if (myMDIChild != null)
            {
                myMDIChild.TopMost = true;
                myMDIChild.Activate();
                myMDIChild.Focus();
                return true;
            }
            return false;
        }
    }
}
